package com.juyu.miliao.api.controller;

import com.juyu.miliao.api.domain.FindDynamicGiftInfo;
import com.juyu.miliao.api.domain.FindDynamicInfo;
import com.juyu.miliao.api.domain.Gift;
import com.juyu.miliao.api.domain.GiftSpend;
import com.juyu.miliao.api.domain.dto.FindDynamicGiftInfoDTO;
import com.juyu.miliao.api.service.FindDynamicGiftService;
import com.juyu.miliao.api.service.FindService;
import com.juyu.miliao.api.service.GiftService;
import com.juyu.miliao.api.service.GiftSpendService;
import com.juyu.miliao.api.validator.GiftSpendCheck;
import com.juyu.miliao.common.domain.Subject;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @author xuanqicheng
 */
@RestController
@RequestMapping("/find/dynamic/gift")
public class FindDynamicGiftController {

    @Autowired
    private FindService findService;

    @Autowired
    private GiftSpendService giftSpendService;

    @Autowired
    private FindDynamicGiftService findDynamicGiftService;

    @Autowired
    private GiftService giftService;

    /**
     * 赠送礼物
     */
    @PostMapping("/")
    public void saveGiftSpend(Authentication token,
                              @Validated FindDynamicGiftInfoDTO dynamicGiftInfoDTO,BindingResult bindingResult) throws IOException {

        if(bindingResult.hasErrors()){
            throw  new ConsumeRuntimeException(bindingResult.getFieldError().getDefaultMessage());
        }

        Subject subject = (Subject) token.getPrincipal();

        FindDynamicInfo findDynamicInfo = findService.getFindDynamicByFindId(dynamicGiftInfoDTO.getFindId());

        if (findDynamicInfo != null) {
            GiftSpend giftSpend = new GiftSpend();
            giftSpend.setOutUserId(Integer.parseInt(subject.getId()+""));
            giftSpend.setInUserId(Integer.parseInt(findDynamicInfo.getUserId()+""));
            giftSpend.setGiftId(dynamicGiftInfoDTO.getGiftId());
            giftSpend.setNum(dynamicGiftInfoDTO.getNum());
            giftSpendService.saveGiftSpend(giftSpend);

            Gift gift =giftService.getGiftById(dynamicGiftInfoDTO.getGiftId());
            FindDynamicGiftInfo findDynamicGiftInfo = new FindDynamicGiftInfo();
            findDynamicGiftInfo.setFindId(dynamicGiftInfoDTO.getFindId());
            findDynamicGiftInfo.setSendId(giftSpend.getSpendId());
            findDynamicGiftInfo.setSendUserId(subject.getId());
            findDynamicGiftService.addGiftSpend(findDynamicInfo,gift,findDynamicGiftInfo);

        }


    }
}
